package com.yb.bluetooth

import android.Manifest
import android.bluetooth.BluetoothDevice
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import com.yb.bluetooth.adapter.BtDeviceListAdapter
import com.yb.bluetooth.entity.BtItem
import com.yb.bluetooth.entity.BtMessage
import com.yb.bluetooth.normal.BtAction
import com.yb.bluetooth.normal.BtUtils
import com.yb.bluetooth.util.LiveBus
import com.yb.bluetooth.util.TempDataUtils
import com.yb.bluetooth.widgets.NoScrollListView
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.yb.bluetooth.util.LocationUtils
import java.util.*

class MainActivity : AppCompatActivity() {

    private val lvPaired by lazy(LazyThreadSafetyMode.NONE) {  findViewById<NoScrollListView>(R.id.lv_paired)  }
    private val lvScan by lazy(LazyThreadSafetyMode.NONE) {  findViewById<NoScrollListView>(R.id.lv_scan)  }
    private val lvConnect by lazy(LazyThreadSafetyMode.NONE) {  findViewById<NoScrollListView>(R.id.lv_connect)  }
    private val linearScan by lazy(LazyThreadSafetyMode.NONE) {  findViewById<LinearLayout>(R.id.linear_scan)  }


    private val mScanAdapter by lazy {
        BtDeviceListAdapter().apply {
            lvScan.adapter = this
            lvScan.setOnItemClickListener { _, _, position, _ ->
                onConnectItemClick(getItem(position))
            }
        }
    }

    private val mPairedAdapter by lazy {
        BtDeviceListAdapter().apply {
            lvPaired.adapter = this
            lvPaired.setOnItemClickListener { _, _, position, _ ->
                onConnectItemClick(getItem(position))
            }
        }
    }

    private fun onConnectItemClick(item: BtItem) {
        if (BtUtils.isConnected(item.deviceAddress)) {
            return ToastUtils.showShort("已连接")
        }
        BtUtils.connectDevice(item.deviceAddress)
    }

    private val mConnectAdapter by lazy {
        BtDeviceListAdapter().apply {
            lvConnect.adapter = this
            lvConnect.setOnItemClickListener { _, _, position, _ ->
                onConnectedClick(getItem(position))
            }
        }
    }

    private var mIsJump = false

    companion object {
        const val DATA = "DATA"
        const val DISCONNECT = "DISCONNECT"
        const val REQUEST_CODE = 22

    }

    private fun onConnectedClick(item: BtItem) {
        mIsJump = true
        val intent = Intent(this, OtherActivity::class.java)
        intent.putExtra(DATA, item)
        startActivityForResult(intent, REQUEST_CODE)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "传统蓝牙"
        BtUtils.init(this, UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66"))
        PermissionUtils.permission(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.BLUETOOTH_ADMIN
        ).request()
        BtUtils.setBtListener(::onState, ::onReceive)
    }

    private fun onState(device: BluetoothDevice, action: BtAction, e: Exception?) {
        val item = BtItem.of(device.name, device.address)
        when (action) {
            BtAction.STATE_CONNECT -> {
                ToastUtils.showShort("蓝牙设备${device.name}已连接")
                if (!mConnectAdapter.data.contains(item))
                    mConnectAdapter.addData(item)
            }
            BtAction.STATE_DISCONNECT -> {
                ToastUtils.showShort("蓝牙设备${device.name}断开连接")
                if (mConnectAdapter.data.contains(item)) {
                    mConnectAdapter.remove(item)
                    LiveBus.post(BtMessage.of(device.address, DISCONNECT))
                }

            }
            BtAction.STATE_CONNECT_FAILED -> {
                ToastUtils.showShort("蓝牙设备${device.name}连接失败")
            }
        }
    }

    private fun onReceive(device: BluetoothDevice, message: String) {
        ToastUtils.showShort("${device.name}：${message}")
        if (mIsJump) {
            LiveBus.post(BtMessage.of(device.name, message))
        } else {
            TempDataUtils.putTempMeg(device.address, "${device.name}：${message}")
        }
    }


    override fun onStart() {
        super.onStart()
        if (!BtUtils.isEnabled()) {
            BtUtils.openBluetooth(this) { if (it) initSettings() }
            return
        }
        initSettings()
    }

    private fun initSettings() {
        BtUtils.startAccept("TEST")
        BtUtils.getPairedDevices()
            ?.map { BtItem.of(it.name, it.address) }
            ?.toMutableList()
            ?.let { mPairedAdapter.setList(it) }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when(item.itemId){
            R.id.action_scan ->{
                val visible = linearScan.isVisible
               linearScan.isVisible = !visible
                if (!LocationUtils.isLocationEnabled(this)) {
                    AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("扫描蓝牙需要位置信息，是否开启？")
                        .setPositiveButton("开启") { _, _ ->
                            LocationUtils.openLocation(this) {
                                if (!it) return@openLocation ToastUtils.showShort("请您开启位置信息")
                                mScanAdapter.setList(mutableListOf())
                                BtUtils.scanDevice(::onScanDeviceResult)
                            }

                        }.show()
                } else {
                    mScanAdapter.setList(mutableListOf())
                    BtUtils.scanDevice(::onScanDeviceResult)
                }
            }
            R.id.action_discoverable ->{
                BtUtils.enableDiscoverable(this) {
                    ToastUtils.showShort(if (it) "已开启" else "已拒绝")
                }
            }
        }
        return true
    }


    private fun onScanDeviceResult(device: BluetoothDevice?) {
        if (device?.name?.isNotEmpty() == true) {
            mScanAdapter.addData(BtItem.of(device.name ?: "未知名称", device.address))
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE) {
            mIsJump = false
        }
    }


}